<template>
  <view class="ladder-wrap">
    <view class="season">
      <view class="season-label">{{ activeSeason.name }}</view>
      <view class="select-btn">
        <u-button type="success" size="mini" @click="selectorShow = true">
          选择赛季
        </u-button>
      </view>
    </view>
    <view>
      <view class="contaier" style="background-color: #FFFFFF;">
        <view class="top_bg">
          <image class="top_bg_img" src="../../static/rank_bg.png" />
          <view class="one_box">
            <!-- 第二名 -->
            <view class="top3" @click="openCharts(list[1])">
              <view class="num_two">
                <image class="huangguan2" src="../../static/two.png"></image>
                <image class="top3_head" :src="list[1].avatarUrl"></image>
                <view class="top_name">{{ list[1].nickName }}</view>
                <view class="top_sy">{{ list[1].totalpoints }}</view>
              </view>
            </view>

            <!-- 第一名 -->
            <view class="top3" @click="openCharts(list[0])">
              <view class="num_one">
                <image class="huangguan1" src="../../static/one.png"></image>
                <image class="top3_head" :src="list[0].avatarUrl"></image>
                <view class="top_name text-bold" style="font-size: 30rpx;">{{
                  list[0].nickName
                }}</view>
                <view class="top_sy">{{ list[0].totalpoints }}</view>
              </view>
            </view>

            <!-- 第三名 -->
            <view class="top3" @click="openCharts(list[2])">
              <view class="num_three">
                <image class="huangguan2" src="../../static/three.png"></image>
                <image class="top3_head" :src="list[2].avatarUrl"></image>
                <view class="top_name">{{ list[2].nickName }}</view>
                <view class="top_sy">{{ list[2].totalpoints }}</view>
              </view>
            </view>
          </view>
        </view>

        <view class="rankList_box">
          <view class="rankItem" v-for="(item, index) in restList" :key="index" @click="openCharts(item)">
            <view class="rankIndex">
              <text>{{ index + 4 }}</text>
            </view>
            <view class="HeardBox">
              <image class="rankHeard" :src="item.avatarUrl"></image>
            </view>

            <view class="NameBox">
              <view class="userName text-bold">{{ item.nickName }}</view>
              <view class="userPost text-gray">{{ item.post }}</view>
              <view class="color_ccc"
                >{{ item.province }} ｜
                <text class="text-blue">{{ item.totalpoints }}</text></view
              >
            </view>
          </view>
        </view>
      </view>
    </view>

    <u-select
      v-model="selectorShow"
      mode="single-column"
      :list="selectSeasons"
      @confirm="handleSelect"
    ></u-select>
  </view>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Season } from "@/types/season";
import { LabelValue } from "@/pages/index/index.vue";
import { UserInfo } from '@/types';

@Component({
  components: {},
})
export default class extends Vue {
  public activeSeason: Season = {};

  public selectorShow = false;

  public get title(): string {
    return `第 ${
      this.activeSeason && this.activeSeason.order
        ? this.activeSeason.order + 1
        : 1
    } 赛季积分排行榜`;
  }

  public get selectSeasons(): LabelValue[] {
    return this.$$store.seasons.map((season: Season) => ({
      label: season.name as string,
      value: season,
    }));
  }

  list = [] as any[];

  restList = [] as any[];

  async onLoad(param: any | {}) {
    console.log("ladder page onload, param:", param);
    // 判断是否已登录
    let userInfo = wx.getStorageSync("user-info");

    if (!userInfo) {
      wx.redirectTo({
        url: "/pages/auth/index",
      });
    }
  }

  onShow() {
    this.init();
  }

  init() {
    this.activeSeason = this.$$store.seasons[0];
    this.$$mutations.updateSeason(this.activeSeason);
    this.loadRanks();
  }

  public handleSelect(event: LabelValue[]): void {
    this.activeSeason = event[0].value;
    this.$$mutations.updateSeason(this.activeSeason);
    this.loadRanks();
  }

  private loadRanks(): void {
    const that = this;
    wx.showLoading({ title: "别急哦...", mask: true });
    // 调用云函数
    wx.cloud
      .callFunction({
        name: "get_user_info",
      })
      .then(({ result }) => {
        wx.hideLoading();
        console.log("[云函数] [get_user_info] 调用成功: ", result);
        if (Array.isArray(result) && result.length > 0) {
          result.forEach((ele) => {
            const seasonActivitiesList = ele.activities.filter(
              (item: any) => item.seasonId === this.activeSeason._id
            );
            const totalpoints = seasonActivitiesList.reduce(
              (prev: any, next: any) => {
                return prev + Number(next.score);
              },
              0
            );
            ele.totalpoints = totalpoints;
          });
          result.sort((prev: any, next: any) => {
            return Number(next.totalpoints) - Number(prev.totalpoints);
          });
          that.list = result;
          that.restList = result.slice(3);
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("[云函数] [get_user_info] 调用失败", err);
      });
  }

  updateUsersData(res: any) {
    for (let i = 0; i < res.length; i++) {
      // 调用云函数
      wx.cloud
        .callFunction({
          name: "modify_score",
          data: {
            activityId: res[i].activityId,
            userId: res[i].userId,
            seasonId: res[i].seasonId,
            score: +res[i].score,
          },
        })
        .then(() => {
          console.log("[云函数] [modify_score] 调用成功!");
        })
        .catch((err) => {
          console.log("[云函数] [modify_score] 调用失败: ", err);
        });
    }
  }

  openCharts(user: UserInfo) {
    wx.navigateTo({
      url: '/pages/ladder/charts?userId=' + user.id
    });
  }
}
</script>

<style lang="scss" scoped>
.ladder-wrap {
  padding: 32rpx;
}

.season {
  display: flex;
  width: 100%;
  height: 80rpx;
  background: cornflowerblue;
  border-radius: 4rpx;
  justify-content: center;
  align-items: center;
  color: white;
  .select-btn {
    margin-left: 20rpx;
  }
}

.top_bg {
  height: 650rpx;
  background-size: 750rpx;
  position: relative;
}

.top_bg_img {
  width: 100%;
  height: 650rpx;
}

.one_box {
  height: 260rpx;
  position: absolute;
  left: 0;
  bottom: 110rpx;
  display: flex;
  justify-content: space-around;
}

.one_box .top3 {
  width: 210rpx;
  height: 280rpx;
}

.top_name {
  width: 100%;
  height: 55rpx;
  line-height: 60rpx;
  color: #f2f2f2;
  font-size: 26rpx;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.top_sy {
  width: 100%;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.top_sy span {
  font-size: 20rpx !important;
}

.num_one {
  position: relative;
}

.huangguan1 {
  width: 60px;
  height: 60px;
  position: absolute;
  right: -10rpx;
  top: -18 * 2rpx;
}

.num_one .top3_head {
  width: 150rpx;
  height: 150rpx;
  border-radius: 100%;
  margin: 15rpx 0 0 30rpx;
  border: 4rpx solid #ffdd3c;
}

.num_two {
  position: relative;
}

.huangguan2 {
  width: 100rpx;
  height: 100rpx;
  position: absolute;
  right: 15rpx;
}

.num_two .top3_head {
  width: 120rpx;
  height: 120rpx;
  border-radius: 100%;
  margin: 45rpx 0 0 45rpx;
  border: 4rpx solid #bcdcdf;
}

.num_three {
  position: relative;
}

.huangguan2 {
  width: 100rpx;
  height: 100rpx;
  position: absolute;
  right: 15rpx;
}

.num_three .top3_head {
  width: 120rpx;
  height: 120rpx;
  border-radius: 100%;
  margin: 45rpx 0 0 45rpx;
  border: 4rpx solid #e29d85;
}

// 列表
.rankList_box {
  min-height: 200rpx;
}

.rankItem:last-child {
  border: none;
}

.rankItem {
  height: 140rpx;
  margin: 0px auto;
  border-bottom: 1px solid #e9e9e9;
}

.rankIndex {
  width: 60rpx;
  height: 140rpx;
  line-height: 140rpx;
  text-align: center;
  color: #cccccc;
  font-size: 40rpx;
  float: left;
}

.HeardBox {
  width: 100rpx;
  height: 100rpx;
  margin: 20rpx;
  border-radius: 100%;
  overflow: hidden;
  float: left;
  margin-right: 25rpx;
  margin-left: 10rpx !important;
}

.HeardBox image {
  width: 100%;
  height: 100%;
}

.NameBox {
  width: 400rpx;
  height: 140rpx;
  float: left;
  padding-top: 10rpx;
  box-sizing: border-box;
}

.NameBox view {
  height: 50rpx;
  line-height: 70rpx;
}

.userName {
  min-width: 90rpx;
  font-size: 30rpx;
  float: left;
  margin-right: 20rpx;
}
</style>
